// 后台脚本：图书增删改、查看借阅记录与统计
document.addEventListener('DOMContentLoaded', () => {
  loadBooks();
  loadAllBorrowRecords();
  loadStats();

  document.getElementById('bookForm').addEventListener('submit', onBookFormSubmit);
  document.getElementById('refreshStats').addEventListener('click', loadStats);
});

async function loadBooks() {
  try {
    const res = await fetch('/api/books');
    const books = await res.json();
    const tb = document.getElementById('bookList');
    tb.innerHTML = '';
    books.forEach(b => {
      const tr = document.createElement('tr');
      tr.innerHTML = `<td>${esc(b.title)}</td><td>${esc(b.author)}</td><td>${esc(b.isbn)}</td><td>${b.publish_year||''}</td>
        <td>${b.available?'是':'否'}</td>
        <td>
          <button data-id="${b.id}" class="edit-btn">编辑</button>
          <button data-id="${b.id}" class="delete-btn">删除</button>
        </td>`;
      tb.appendChild(tr);
    });
    tb.querySelectorAll('.edit-btn').forEach(b=>b.addEventListener('click', onEditBook));
    tb.querySelectorAll('.delete-btn').forEach(b=>b.addEventListener('click', onDeleteBook));
  } catch (e) { console.warn(e); }
}

async function onBookFormSubmit(e) {
  e.preventDefault();
  const id = document.getElementById('bookId').value;
  const payload = {
    title: document.getElementById('title').value,
    author: document.getElementById('author').value,
    isbn: document.getElementById('isbn').value,
    publish_year: Number(document.getElementById('publishYear').value) || 0,
    available: document.getElementById('available').value === 'true'
  };
  try {
    if (id) {
      await fetch(`/api/books/${id}`, { method:'PUT', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) });
    } else {
      await fetch('/api/books', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload) });
    }
    document.getElementById('bookForm').reset();
    document.getElementById('bookId').value = '';
    await loadBooks();
  } catch (e) { alert('保存失败'); }
}

function onEditBook(e) {
  const id = e.currentTarget.dataset.id;
  fetch(`/api/books/${id}`).then(r=>r.json()).then(b=>{
    document.getElementById('bookId').value = b.id;
    document.getElementById('title').value = b.title || '';
    document.getElementById('author').value = b.author || '';
    document.getElementById('isbn').value = b.isbn || '';
    document.getElementById('publishYear').value = b.publish_year || '';
    document.getElementById('available').value = b.available ? 'true' : 'false';
    window.scrollTo(0,0);
  });
}

async function onDeleteBook(e) {
  const id = e.currentTarget.dataset.id;
  if (!confirm('确认删除？')) return;
  await fetch(`/api/books/${id}`, { method:'DELETE' });
  await loadBooks();
}

async function loadAllBorrowRecords() {
  try {
    const res = await fetch('/api/borrow_records');
    const records = await res.json();
    const [booksRes, usersRes] = await Promise.all([fetch('/api/books'), fetch('/api/users?page=1&page_size=500')]);
    const books = await booksRes.json();
    const users = await usersRes.json();
    const bookMap = {}, userMap = {};
    books.forEach(b=>bookMap[b.id]=b);
    users.forEach(u=>userMap[u.id]=u);

    const tb = document.getElementById('allBorrowList'); tb.innerHTML = '';
    records.forEach(rec => {
      const tr = document.createElement('tr');
      tr.innerHTML = `<td>${rec.id}</td>
        <td>${esc((bookMap[rec.book_id]||{}).title||'')}</td>
        <td>${esc((userMap[rec.user_id]||{}).name||'')}</td>
        <td>${fmt(rec.borrowed_at)}</td>
        <td>${fmt(rec.due_at)}</td>
        <td>${rec.returned?fmt(rec.returned_at):'否'}</td>`;
      tb.appendChild(tr);
    });
  } catch (e) { console.warn(e); }
}

async function loadStats() {
  try {
    const res = await fetch('/api/stats/overview');
    const ov = await res.json();
    document.getElementById('overview').textContent = JSON.stringify(ov, null, 2);

    const tr = await fetch('/api/stats/top-borrowed?n=10');
    const top = await tr.json();
    const ol = document.getElementById('topBorrowed'); ol.innerHTML = '';
    top.forEach(it => {
      const li = document.createElement('li');
      li.textContent = `${it.title} — ${it.count} 次`;
      ol.appendChild(li);
    });
  } catch (e) { console.warn(e); }
}

function esc(s){ if (!s) return ''; return String(s).replace(/[&<>"']/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m])); }
function fmt(v){ if (!v) return ''; try { const d=new Date(v); return isNaN(d)?v:d.toLocaleString(); } catch(e){ return v; } }